package com.chou.sts.controller;

import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import com.chou.sts.domain.Student;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController 
{	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	//private StudentService studentService;
	@Autowired
	private RestTemplate restTemplate;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) 
	{
		logger.info("Welcome home page! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);		
		model.addAttribute("serverTime", formattedDate );
		return "home";
	}
	
	@RequestMapping(value = "students", method = RequestMethod.GET)
	public String students(Model model) 
	{
		logger.info("Welcome Students Page!");
		Student[] list = restTemplate.getForObject("http://localhost:8080/sts/api/students", Student[].class);
		List<Student> students = Arrays.asList(list);
		model.addAttribute("students", students);
		return "studentlist";
	}
	
	@RequestMapping(value = "student/{id}", method = RequestMethod.GET)
	public String student(@PathVariable int id, Model model) 
	{
		logger.info("Welcome Student Page!");
		Student student = restTemplate.getForObject("http://localhost:8080/sts/api/student/{id}", Student.class, id);
		model.addAttribute("student", student);
		return "student";
	}
}
